package com.example.stompdemo.test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SendToUser;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;

import java.security.Principal;
import java.util.Map;

/**
 * date 2021/3/5
 */
@RestController
@RequestMapping("/webSocket")
@MessageMapping("foo")
public class WebSocketController {

    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    /**
     * 精准推送
     * @param map
     * @return
     */
    @MessageMapping("handle1")
//    @SendToUser(value = "/topic/greetings1",broadcast = false)  //注解的方式 类似于广播，如果是单个用户之间发送消息使用simpMessagingTemplate.convertAndSendToUser
    public void handle1(Map<String,String> map, Principal principal) {
        String msg = map.get("msg");
        String toUser = map.get("toUser");
        simpMessagingTemplate.convertAndSendToUser(toUser, "/topic/greetings1", msg);
    }


    /**
     * 广播推送
     * @param msg
     * @param principal
     * @return
     */
    @MessageMapping("handle2")
    @SendTo("/topic/greetings2")
    public String handle2(String msg,Principal principal) {

        return "广播推送，所有用户都收得到";
    }
}